﻿using BLLFactory;
using Common;
using Demo.Models;
using IBLL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace Demo.Controllers
{
    public class AuthController : ApiController
    {
        private readonly ISysUserService SysUserService = Container.Resolve<ISysUserService>();
        [HttpPost]
        public async Task<LoginResult> Login([FromBody] LoginRequest request)
        {
            LoginResult rs = new LoginResult();
            Data data = new Data();
            Sys_User user = await SysUserService.GetModelAsync(request.Name, request.Password);
            if (user == null)
            {
                rs.Message = "账户或密码错误";
                rs.Success = false;
            }
            else
            {
                UserModel info = new UserModel { id=user.Id, name = user.UserName, position = user.Position };
                try
                {
                    data.token = JwtHelper.GetToken(info.id.ToString());
                    data.user = info;
                    data.expireAt = DateTime.Now.AddHours(3);
                    rs.Message = "登陆成功";
                    rs.Success = true;
                    rs.data = data;
                }
                catch (Exception ex)
                {
                    rs.Message = ex.Message;
                    rs.Success = false;
                }
            }
            return rs;
        }
    }
}